import psutil
import time
import datetime
import os

from flask import Blueprint
from flask import g, jsonify, request
from scapy.all import *
from all.tools.deletefile import delete


ips_blueprint = Blueprint('ips', __name__, url_prefix='/ips')

@ips_blueprint.route('/delete', methods=['GET'])
def handle():
    delete()
    return "success"

@ips_blueprint.route('',methods=['GET'])
def get_ips():
    FILE_DIR = 'all/pcaps/'
    data = []
    ITEMS = os.listdir(FILE_DIR)
    NEWLIST = []
    for names in ITEMS:
        if names.endswith(".pcap"):
            NEWLIST.append(FILE_DIR + names)
    for names in NEWLIST:
        date = datetime.fromtimestamp(os.path.getmtime(names))
        now = datetime.now()
        #print((now-date).seconds)
        if (now - date).seconds < 1000:
            #print("------------------------------------------")
            pkts = PcapReader(names)
            for pkt in pkts:
                try:
                    #print(pkt['IP'].proto)
                    data.append({
                        "src":pkt['IP'].src,
                        "dst":pkt['IP'].dst,
                        "proto":pkt['IP'].proto,
                        "len":pkt['IP'].len,
                    })
                except:
                    pass
    return jsonify(data)
